package com.airpi.activities;

import java.io.File;

import com.airpi.listeners.RightDrawableOnTouchListener;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v4.app.Fragment;
import android.text.InputType;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.airpi.R;
import com.airpi.connectivity.PathManager;
import com.airpi.heavy_tasks.AsyncTaskFragment;
import com.airpi.heavy_tasks.AsyncTaskStreaming;

public class MainMiddleFragment extends Fragment implements OnClickListener, Observer{
	//Initialisation of the two List Views (User List and Media List)
	ArrayAdapter<String> adapter;
	private boolean isPlaying;

	//Initialisation of the different buttons
	private ImageButton playButton;
	private ImageButton nextButton;
	private ImageButton stopButton;
	private ImageButton volumeDownButton;
	private ImageButton volumeUpButton;
	private Button browseButton;
	private Button uploadButton;
	private TextView uploadInformation;
	private EditText youtubeURL;
	private File file;
	
	private ProgressBar spinnerUpload;
	private ProgressBar spinnerURL;
	
	private Intent data;

	/**
	 * Method called on the generation of the main UI view, handling the different fragments
	 * On generation of the View, it inflates the layout of the different tabs
	 */

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(getActivity());
		View rootView;

		//Inflate the Main UI View and the different buttons
		rootView = inflater.inflate(R.layout.main_main_ui, container, false);

		playButton = (ImageButton) rootView.findViewById(R.id.main_imgb_play);
		nextButton = (ImageButton) rootView.findViewById(R.id.main_imgb_next);
		stopButton = (ImageButton) rootView.findViewById(R.id.main_imgb_stop);
		volumeDownButton = (ImageButton) rootView.findViewById(R.id.main_imgb_volume_minus);
		volumeUpButton = (ImageButton) rootView.findViewById(R.id.main_imgb_volume_plus);
		browseButton = (Button) rootView.findViewById(R.id.main_browse_button);
		uploadButton = (Button) rootView.findViewById(R.id.main_upload_button);
		uploadInformation = (TextView) rootView.findViewById(R.id.main_upload_information_textview);
		youtubeURL = (EditText) rootView.findViewById(R.id.main_url_edittext);
		
		spinnerUpload = (ProgressBar)rootView.findViewById(R.id.main_upload_progressbar);
		spinnerURL = (ProgressBar)rootView.findViewById(R.id.main_url_progressbar);
	    spinnerUpload.setVisibility(View.GONE);
	    spinnerURL.setVisibility(View.GONE);

		//Set the listener on these buttons
		playButton.setOnClickListener(this);
		nextButton.setOnClickListener(this);
		stopButton.setOnClickListener(this);
		volumeDownButton.setOnClickListener(this);
		volumeUpButton.setOnClickListener(this);
		browseButton.setOnClickListener(this);
		uploadButton.setOnClickListener(this);

		youtubeURL.setOnTouchListener(new RightDrawableOnTouchListener(youtubeURL) {
			@Override
			public boolean onDrawableTouch(MotionEvent event) {
				return onClickSearch(youtubeURL);
			}

		});
		
		new Thread() {
			private AsyncTaskFragment atc;
			private Fragment f;

			public Thread set(Fragment f) {
				this.f = f;
				return this;
			}
			
			@Override
			public void run() {
				while(true) {
					try {
						atc = new AsyncTaskFragment(((Observer)f), "State");
						atc.execute();
						Thread.sleep(3000);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
			}
		}.set(this).start();

		if(!sharedPrefs.getBoolean(LoginActivity.USER_STATUS,false))
			((LinearLayout)rootView.findViewById(R.id.main_button_bar)).setVisibility(View.GONE);


		return rootView;
	}

	/**
	 * Send a request which contains the YouTube URL to the server
	 * @param view The {@link EditText}
	 * @return Always false
	 */
	private boolean onClickSearch(final View view) {
		if (!youtubeURL.getText().toString().equals(""))
			spinnerURL.setVisibility(View.VISIBLE);
		
		final SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(getActivity());
		AsyncTaskFragment atcYT = new AsyncTaskFragment(this, "Youtube:"+youtubeURL.getText().
				toString()+";"+sharedPrefs.getString(LoginActivity.LOGIN_USER, null));
		atcYT.execute();
		return false;
	}

	/**
	 * Method handling the different click on the buttons, sending the correct 
	 * request to the server depending on the button clicked.
	 * Except for the Browse case, which open the file selection menu
	 */

	@Override
	public void onClick(View v) {
		switch(v.getId()){
		case R.id.main_imgb_play:
			if(isPlaying){
				AsyncTaskFragment atcState = new AsyncTaskFragment(this, "Pause");
				atcState.execute();
			}else{
				AsyncTaskFragment atcState = new AsyncTaskFragment(this, "Play");
				atcState.execute();
			}break;
		case R.id.main_imgb_next:
			AsyncTaskFragment louis = new AsyncTaskFragment(this, "Next");
			louis.execute();
			break;
		case R.id.main_imgb_stop:
			AsyncTaskFragment atcS = new AsyncTaskFragment(this, "Stop");
			atcS.execute();
			break;
		case R.id.main_imgb_volume_minus:
			AsyncTaskFragment atcVM = new AsyncTaskFragment(this, "VolumeDown");
			atcVM.execute();
			break;	
		case R.id.main_imgb_volume_plus:
			AsyncTaskFragment atcVP = new AsyncTaskFragment(this, "VolumeUp");
			atcVP.execute();
			break;
		case R.id.main_browse_button:
			Intent selectFile = new Intent(Intent.ACTION_GET_CONTENT, null);
			selectFile.setType("audio/*, video/*");
			startActivityForResult(selectFile, 1);
			break;
		case R.id.main_upload_button:
			if (this.data != null)
				spinnerUpload.setVisibility(View.VISIBLE);
			AsyncTaskStreaming ats = new AsyncTaskStreaming(this);
			ats.execute((Void[]) null);
			break;
		}
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (data != null) {
			this.data = data;
			Log.d("MainActivity", PathManager.getPath(getActivity(), data.getData()));
			this.file = new File(PathManager.getPath(getActivity(), data.getData()));
			uploadInformation.setTextColor(Color.GRAY);
			uploadInformation.setText(file.getName());
		}
	}
	

	/**
	 * Gets the selected file 
	 * @return The selected file
	 */
	public File getFile() {
		return file;
	}
	
	/**
	 * Sets the spinner at the right of the upload button
	 * @param state True to set visibility to "visible" and false to set visibility to "gone"
	 */
	public void setSpinnerUpload(boolean state) {
		if (state == true)
			spinnerUpload.setVisibility(View.VISIBLE);
		else 
			spinnerUpload.setVisibility(View.GONE);
	}
	
	/**
	 * Sets the spinner below the URL {@link EditText}
	 * @param state True to set visibility to "visible" and false to set visibility to "gone"
	 */
	public void setSpinnerURL(boolean state) {
		if (state == true)
			spinnerURL.setVisibility(View.VISIBLE);
		else 
			spinnerURL.setVisibility(View.GONE);
	}
	
	/**
	 * Gets the {@link TextView} which informs the user about file upload
	 * @return The {@link TextView}
	 */
	public TextView getUploadInformation() {
		return uploadInformation;
	}

	/**
	 * Sets the {@link TextView} which informs the user about file upload
	 * @param uploadInformation The {@link TextView} which informs the user about file upload
	 */
	public void setUploadInformation(TextView uploadInformation) {
		this.uploadInformation = uploadInformation;
	}

	@Override
	public void notifier(String s) {
		System.out.println("result = " + s);
		if(s.contains("State")){
			String state = s.split(":")[1];
			int playing = Integer.valueOf(state.split(";")[0]);
			int stopped = Integer.valueOf(state.split(";")[1]);
			if(playing == 1){
				this.isPlaying=true;
				this.stopButton.setEnabled(true);
				this.nextButton.setEnabled(true);
				this.playButton.setEnabled(true);
				this.playButton.setImageResource(R.drawable.pause);
			}
			if(playing == 0){
				this.isPlaying=false;
				this.stopButton.setEnabled(true);
				this.nextButton.setEnabled(true);
				this.playButton.setEnabled(true);
				this.playButton.setImageResource(R.drawable.play);
			}
			if(stopped == 0){
				this.stopButton.setEnabled(true);
				this.nextButton.setEnabled(true);
				this.playButton.setEnabled(true);
			}
			if(stopped == 1){
				this.stopButton.setEnabled(false);
				this.nextButton.setEnabled(true);
				this.playButton.setEnabled(true);
				this.playButton.setImageResource(R.drawable.play);
			}
		}else if(s.contains("Play") || s.contains("Pause") || s.contains("Stop") || s.contains("Next")){
			AsyncTaskFragment atcVP = new AsyncTaskFragment(this, "State");
			atcVP.execute();
		}else if(s.contains("Delete")){
			AsyncTaskFragment atcUs = new AsyncTaskFragment(this, "MediaList");
			atcUs.execute();
		}
	}
}
